import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  cache: {
    setStoreValue: (key: string, value: any) => {
      ipcRenderer.send('setStore', key, value)
    },
    getStoreValue(key: string) {
      const resp = ipcRenderer.sendSync('getStore', key)
      return resp
    },
    removeStore(key: string) {
      ipcRenderer.send('removeStore', key)
    },
    clear() {
      ipcRenderer.send('clearStore')
    }
  },
  log: {
    v(tag: string, message: string) {
      ipcRenderer.send('logger', 0, tag, message)
    },
    d(tag: string, message: string) {
      ipcRenderer.send('logger', 1, tag, message)
    },
    i(tag: string, message: string) {
      ipcRenderer.send('logger', 2, tag, message)
    },
    w(tag: string, message: string) {
      ipcRenderer.send('logger', 3, tag, message)
    },
    e(tag: string, message: string) {
      ipcRenderer.send('logger', 4, tag, message)
    }
  },
  httpHistory: {
    saveRequest: (data: any) => ipcRenderer.invoke('save-http-request', data),
    loadRequests: () => ipcRenderer.invoke('load-http-requests'),
    deleteRequest: (id: number) => ipcRenderer.invoke('delete-http-request', id),
    updateRequest: (data: any) => ipcRenderer.invoke('update-http-request', data)
  },
  invoke: (channel: string, ...args: any[]) => {
    const validChannels = ['proxy-http-request', /* other valid channels */]
    if (validChannels.includes(channel)) {
      return ipcRenderer.invoke(channel, ...args)
    }
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
